package org.jeecg.modules.login.api;

import me.chanjar.weixin.cp.bean.WxCpOauth2UserInfo;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.login.LoginService;
import org.jeecg.config.thirdapp.ThirdAppConfig;
import org.jeecg.modules.login.handler.wechat.WeChatEnterpriseHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * [企业微信] 扫码登录
 *
 * @author tianyi.jiang
 * @since 1.2.2
 */
@RestController
@RequestMapping("/sys/wechat/enterprise")
@ConditionalOnExpression("'${basicplatform.login.wechat-enterprise-qr.enable:false}'.equals('true')")
public class WeChatEnterpriseQrLogin {

    private final WeChatEnterpriseHandler weChatEnterpriseHandler;

    private final WeChatEnterpriseHandler.WeChatEnterpriseProperty weChatEnterpriseProperty;

    private final LoginService loginService;

    @GetMapping("/auth/parameter")
    public Result<?> weChatQrUrl() {
        Map<String, String> map = new HashMap<String, String>(3) {{
            this.put("redirectUri", weChatEnterpriseProperty.getAuthUrl());
            this.put("appId", weChatEnterpriseProperty.getCorpId());
            this.put("agentId", String.valueOf(weChatEnterpriseProperty.getAgentId()));
        }};
        return Result.OK(map);
    }

    @GetMapping("/auth")
    public Result<?> weChatLogin(@RequestParam("code") String code) {
        WxCpOauth2UserInfo wxCpOauth2UserInfo = weChatEnterpriseHandler.weChatUser(code);
        String weChatUserId = wxCpOauth2UserInfo.getUserId();
        return loginService.authByThirdAccount(weChatUserId, ThirdAppConfig.WECHAT_ENTERPRISE);
    }

    public WeChatEnterpriseQrLogin(WeChatEnterpriseHandler weChatEnterpriseHandler, WeChatEnterpriseHandler.WeChatEnterpriseProperty weChatEnterpriseProperty, LoginService loginService) {
        this.weChatEnterpriseHandler = weChatEnterpriseHandler;
        this.weChatEnterpriseProperty = weChatEnterpriseProperty;
        this.loginService = loginService;
    }
}